package com.android.enjoymax;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapController;
import com.google.android.maps.Overlay;
import com.yelp.v2.Business;
import com.yelp.v2.Categories;
import com.yelp.v2.Center;

public class YelpActivity extends Activity {

	public static final String URL = "http://api.yelp.com/business_review_search";
	public static final String KEY = "OtMtfEOAmZq_Bk3GJqz37Q";
	public static final String RADIUS = "10";
	public static final String LIMIT = "5";
	
    public static final String TAG = "Loc";
    public static final String CURRENT_LOCATION = "Current Location";
    public static final String MILES = " miles";
    
    public static final long MIN_TIME = 60000;
    public static final float MIN_DISTANCE = 100;
    public static final int ZOOM_LEVEL = 18;
    public static final double FEET_TO_MILES = 0.3048 * 0.00062137119;
    public static 
    
	double latitude = 0.0;
	double longitude = 0.0;
	
	private boolean intentReturn = false;
	
	private LocationManager lm;
	private MyLocationListener locationListener;
	private MapController mapController;
	private SensorManager mSensorManager;
	private GeoPoint pointPresent;
	private MyItemizedOverlay itemizedOverlay;
	private MyItemizedOverlay itemizedOverlayForCurrentLoc;
	private List<Overlay> mapOverlays; 
	
	private ListView listView;
	private ArrayAdapter<String> adapter;
	
    public static boolean flag = true;
	
    private static MTDAppActivity temp;
    
    public static List<String> globalStopIds= new ArrayList<String>();
    
    private static String stopIdSelected;
    
	/** Called when the activity is first created. */  
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
        
//        temp = this;
        lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        locationListener = new MyLocationListener();
        
        lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, locationListener);
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME, MIN_DISTANCE, locationListener);
        
        new RequestTask().execute(new String[] {URL, "Location", "sushi"});
    } 
    
    private GeoPoint coordinatesToGeoPoint(Location location) {
    	final int multiplier = (int) Math.pow(10, 6);
    	final int tempLatitude = (int)(location.getLatitude() * multiplier);
    	final int tempLongitude = (int) (location.getLongitude() * multiplier);
    	return new GeoPoint(tempLatitude, tempLongitude);
    }
    
    private GeoPoint coordinatesToGeoPoint(double latitudeLoc, double longitudeLoc) {
    	final int multiplier = (int) Math.pow(10, 6);
    	final int tempLatitude = (int)(latitudeLoc * multiplier);
    	final int tempLongitude = (int) (longitudeLoc * multiplier);
    	return new GeoPoint(tempLatitude, tempLongitude);
    }

    class MyLocationListener implements LocationListener 
    {
		@Override
		public void onLocationChanged(Location location) {
			longitude = location.getLongitude();
	        latitude = location.getLatitude();
	        
	         Log.d(TAG, "my lat is " + latitude + " and lon is " + longitude);
	         
	         itemizedOverlayForCurrentLoc.resetMap();
	         pointPresent = coordinatesToGeoPoint(location);
	         
	         //Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
	         mapController.animateTo(pointPresent);
	         mapController.setCenter(pointPresent);

	         new RequestTask().execute(new String[] {URL + "Location" + "sushi", "Location"});
		}

		@Override
		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			
			//new RequestTask().execute(new String[] {URL + "GetStopsByLatLon", "GetStopsByLatLon"});
		}
        	
    }
    
    // This is for GetStopsByLatLon webservice call.
    class RequestTask extends AsyncTask<String, Void, String>{
    	
        @Override
        protected String doInBackground(String... uri) {
        	
        	//?term=yelp&lat=37.788022&long=-122.399797&radius=10&limit=5&ywsid=XXXXXXXXXXXXXXXXXX
        	
        	if (uri[1].equals("Location")) {
        		RestClient client = new RestClient(uri[0]);
        		client.addParam("term", uri[2]);
        		client.addParam("lat", String.valueOf(latitude));
        		client.addParam("long", String.valueOf(longitude));
        		client.addParam("radius", RADIUS);
        		client.addParam("limit", LIMIT);
        		client.addParam("ywsid", KEY);
        		//client.addParam("changeset_id", "");

        		try {
        		    client.Execute();
        		} 
        		catch (Exception e) {
        			printToast("Network not reachable");
        		    e.printStackTrace();
        		    return "";
        		}
        		String response = client.getResponse();
        		return response;
        	}
        	return "";
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            //Do anything with response..
            
            try {
            	if (result == "" || result.length() == 0) return;

            	JSONObject jsonObject = new JSONObject(result);
//				List<String> foodPlaces = new ArrayList<String>();
//				List<Double> distanceToFoodPlace = new ArrayList<Double>();
//				final List<String> foodPlaceIdentifier = new ArrayList<String>();

				JSONArray array = jsonObject.getJSONArray("businesses");
				ArrayList<NameValuePair> latLonList = new ArrayList<NameValuePair>();
				
				ArrayList<Business> foodPlaces = new ArrayList<Business>(); 
				
				for(int i = 0 ; i < array.length() ; i++){
					Business tempVar = new Business(); 
					tempVar.setId(array.getJSONObject(i).getString("id")); 
					tempVar.setName(array.getJSONObject(i).getString("name"));
					tempVar.setMobileUrl(array.getJSONObject(i).getString("mobile_url")); 
					tempVar.setImageUrl(array.getJSONObject(i).getString("photo_url")); 
					tempVar.setImageUrlSmall(array.getJSONObject(i).getString("photo_url_small")); 
					tempVar.setReviewCount(Integer.valueOf(array.getJSONObject(i).getString("review_count"))); 
					tempVar.setPhone(array.getJSONObject(i).getString("phone"));
					Center location = new Center(); 
					location.setLatitude(Double.valueOf(array.getJSONObject(i).getString("latitude"))); 
					location.setLongitude(Double.valueOf(array.getJSONObject(i).getString("longitude"))); 
					tempVar.setLocation(location); 

					ArrayList<Categories> categories = new ArrayList<Categories>();
					JSONArray categoryArray = new JSONArray(array.getJSONObject(i).getString("categories"));
					
					for (int j = 0; j < categoryArray.length(); j++) {
						Categories tempCategory = new Categories(); 
						tempCategory.setCategory_filter(categoryArray.getJSONObject(i).getString("category_filter"));
						tempCategory.setName(categoryArray.getJSONObject(i).getString("name")); 
						tempCategory.setSearch_url(categoryArray.getJSONObject(i).getString("search_url")); 
						categories.add(tempCategory); 
					}
					
					tempVar.setCategories(categories);
					tempVar.setUrl(array.getJSONObject(i).getString("url"));
					
					Log.d(TAG, "Business place addeed"); 
					foodPlaces.add(tempVar); 
				}
			} 
            catch (JSONException e) {
				// TODO Auto-generated catch block
            	//printToast("Not able to parse JSON due to invalid input");
				//e.printStackTrace();
			}

        }
    }
    
    void printToast(String str) {
    	Context context = getApplicationContext();
		int duration = Toast.LENGTH_LONG;

		Toast toast = Toast.makeText(context, str, duration);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.show();	
    }

    @Override
    public void onResume() {
        super.onResume();
        //if(D) 
        Log.d(TAG, "+ ON RESUME +");
        
        if (intentReturn == true) {
        	mapController.animateTo(pointPresent);
        	intentReturn = false;
        	new RequestTask().execute(new String[] {URL + "GetStopsByLatLon", "GetStopsByLatLon"});
        }
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.activity_yelp, menu);
        return true;
    }
}
